import {defineConfig} from 'vitepress'
import cesium from '../cesium/cesium'
import article from '../文章/article'

import fs from 'fs';
import path from 'path';
import {fileURLToPath} from 'url';

/**
 * 生成目录结构
 * @param {string} dirPath - 要遍历的目录路径
 * @param {string} [basePath=''] - 基础路径，用于生成link
 * @param {number} [depth=0] - 当前递归深度
 * @param {number} [maxDepth=10] - 最大递归深度
 * @returns {Array} 生成的目录结构数组
 */
function generateDirectoryStructure(
    dirPath,
    basePath = '',
    depth = 0,
    maxDepth = 10
) {
    // 获取目录名作为顶层text
    const dirName = path.basename(dirPath);

    // 初始化结果对象
    const result = {
        text: dirName,
        collapsed: depth > 0, // 默认只有顶层展开
    };

    // 如果达到最大深度，直接返回
    if (depth >= maxDepth) {
        return result;
    }

    try {
        // 读取目录内容
        const items = fs.readdirSync(dirPath, {withFileTypes: true});
        const childItems = [];

        for (const item of items) {
            const fullPath = path.join(dirPath, item.name);
            const relativePath = path.join(basePath, item.name);

            if (item.isDirectory() && item.name !== '.vitepress') {

                // 如果是目录，递归处理
                const childDir = generateDirectoryStructure(
                    fullPath,
                    relativePath,
                    depth + 1,
                    maxDepth
                );
                childItems.push(childDir);
            } else if (item.isFile() && path.extname(item.name) === '.md') {
                // 如果是Markdown文件，添加到items
                childItems.push({
                    text: path.basename(item.name, '.md'),
                    link: `/${relativePath.replace(/\\/g, '/').replace('.md', '')}`,
                });
            }
        }

        // 如果有子项，添加到结果中
        if (childItems.length > 0) {
            result.items = childItems;
        }

        return result;
    } catch (error) {
        console.error(`Error processing directory ${dirPath}:`, error);
        return result;
    }
}



const dirPath = fileURLToPath(new URL('../', import.meta.url))

const structure = generateDirectoryStructure(dirPath, '');


// https://vitepress.dev/reference/site-config
export default defineConfig({

    // base:'./',
    title: "世某人笔记文档",
    description: "世某人文档",
    outDir: '../dist',
    themeConfig: {
        search: {
            provider: 'local'
        },
        lastUpdated: {
            text: '文档最后更新时间：',
            formatOptions: {
                dateStyle: 'full',
                timeStyle: 'medium'
            }
        },

        // https://vitepress.dev/reference/default-theme-config
        nav: [
            ...structure.items,
        ],


        sidebar: {
            '/cesium': cesium,
            '/文章': article,
        },
        socialLinks: [
            {icon: 'github', link: 'https://gitee.com/smren'}
        ]
    }
})
